package org.dromara.common.mqtt.config;


import lombok.extern.slf4j.Slf4j;
import org.dromara.common.mqtt.callback.MqttCallBack;
import org.dromara.common.mqtt.config.properties.MqttProperties;
import org.dromara.common.mqtt.domain.CustomMqttClient;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;

@Slf4j
@AutoConfiguration
@ConditionalOnProperty(value = "mqtt.enabled", havingValue = "true")
@EnableConfigurationProperties(MqttProperties.class)
public class MqttConfig {

    @Autowired
    private MqttCallBack mqttCallBack;

    @Autowired
    private MqttProperties mqttProperties;

    /**
     * 客户端连接
     *
     * @return
     */
    @Bean
    public MqttClient connect() {
        MqttClient client = null;
        try {
            client = new MqttClient(mqttProperties.getHostUrl(), mqttProperties.getClientId(), new MemoryPersistence());
            MqttConnectOptions options = new MqttConnectOptions();
            options.setUserName(mqttProperties.getUsername());
            options.setPassword(mqttProperties.getPassword().toCharArray());
            options.setConnectionTimeout(mqttProperties.getTimeout());
            options.setKeepAliveInterval(mqttProperties.getKeepAlive());
            options.setAutomaticReconnect(mqttProperties.getReconnect());
            options.setCleanSession(mqttProperties.getCleanSession());
            CustomMqttClient.setClient(client);
            // 设置回调
            client.setCallback(mqttCallBack);
            client.connect(options);
        } catch (Exception e) {
            log.error("MqttAcceptClient connect error", e);
        }
        return client;
    }
}
